<script setup>
import { computed, inject, onMounted, ref, reactive } from 'vue'
import { DlMessageBox } from '../util/messagebox.js';
import { IconTopCircle, IconTriangleDown, IconTriangleUp } from '../icon/index.js'
import DlLoading from '../components/DlLoading.vue'
import ProductBox from '../components/ProductBox.vue'
import SearchBox from '../components/SearchBox.vue'

import { getTypesByParentFun } from '../api/type.js'
import { searchProductFun } from '../api/product.js'
import { addToCartFun } from '../api/cart.js'

const currentPageNum = ref(1);
const pageSize = 5;
const pages = ref(0);//总页数
const productArr = ref([]);//数据
const productLoading = ref(false);//加载中
const noMoreData = ref(false);//无更多数据
//加载商品
function doLoadDataProduct() {
    productLoading.value = true;
    noMoreData.value = false;

    //请求参数
    let params = {
        pageNum: currentPageNum.value,
        pageSize: pageSize,
        keyWord: searchKey.value, // 搜索关键字
        sortKey: selectSort.key,// 排序依据
        sort: selectSort.sort, //1 降序, -1 升序
    };
    if(currentBigType) {//大类别
        params.bigType = currentBigType.id;
    }
    if(currentSecondType) {//小类别
        params.secondType = currentSecondType.id;
    }
    // 小类别
    console.log('params:', params);

    if (window && window.enableDl) {
        //模拟
        setTimeout(()=>{
            let dataArr = [];
    
            let key = productArr.value.length + 1;
            for(let i=0; i<5; i++) {
                dataArr.push({id: i+key, title: '测试测试测试测试-'+(i+key), image: './product.jpg', price: 99.99, type:['红色','绿色','蓝色'], status:1});
            }
    
            dataArr.forEach(p => productArr.value.push(p));
            pages.value = 5;
            noMoreData.value = currentPageNum.value >= pages.value;
            productLoading.value = false;
        }, 1000);
    } else {
        //请求api
        searchProductFun(params.pageNum, params.pageSize, params.keyWord, params.sortKey, params.sort, params.bigType, params.secondType)
        .then((result)=>{
            console.log('searchProductFun result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);
                let data = result.data;
                data.list.forEach(p => productArr.value.push(p));
                pages.value = data.pages;
                noMoreData.value = currentPageNum.value >= pages.value;
            } else {
                DlMessageBox.error(result.msg);
            }
            productLoading.value = false;
        });
    }

}

//底部主菜单
const homeMenuBar = inject('homeMenuBar');
const viewRef = ref(null);
const viewHeight = computed(()=>{//计算展示区域高度
    let vh = 770;
    if(viewRef.value) {
        let p = viewRef.value.parentElement;
        vh = p.offsetHeight;
    }
    if(homeMenuBar.value) {
        let h = homeMenuBar.value.offsetHeight;
        vh -= h;
    }
    return vh;
});

let scrollTarget;
//滚动事件
function doChangeScroll(e) {
    // console.log('doChangeScroll:', e);
    let t = e.target;
    scrollTarget = t;
    //回到顶部按钮处理, 显示与隐藏
    showTopBtn.value = t.scrollTop > showHideTop;

    let offsetNum = 10;//误差值
    let height = t.scrollHeight - t.offsetHeight - t.scrollTop - offsetNum;
    // 到底加载更多
    if(height <= 0) {
        console.log('滚动到底部了...');
        //如果还有数据,则加载;如果正在加载中,则不再执行
        if(!productLoading.value && currentPageNum.value < pages.value) {
            currentPageNum.value++;
            doLoadDataProduct();
        }
    }
}
const showTopBtn = ref(false);
const showHideTop = 300;//隐藏和显示的scrollTop
const topBtnStyle = computed(()=>{
    let bottom = 40;
    let right = -1.8;
    if(homeMenuBar.value) {
        let h = homeMenuBar.value.offsetHeight;
        bottom+=h;
    }
    if(showTopBtn.value) {
        right = 0.6;
    }
    return {bottom: bottom+'px', right: right+'rem'};
});
//回到顶部
function doGoTop() {
    if(scrollTarget) {
        scrollTarget.scrollTo({top: 0, behavior: 'smooth'});
    }
}

//左侧大类别
const bigTypeArr = ref([]);
function doLoadBigType() {
    //加载所有大类别
    if (window && window.enableDl) {
        //模拟
        setTimeout(()=>{
            let dataArr = [];
    
            for(let i=0;i<16;i++) {
                dataArr.push({id: i+1, name: '大类别-'+(i+1)});
            }
    
            //成功后执行以下操作
            bigTypeArr.value = dataArr;
            //默认选中的
            let selectBigType = bigTypeArr.value[0];
            // 如果是 在 HomeView 点击分类 跳转来的
            let selectBigTypeId = localStorage.getItem('selectBigTypeId');
            if(selectBigTypeId) {
                //用完清除
                localStorage.removeItem('selectBigTypeId');
                selectBigType = bigTypeArr.value.find(t => t.id == selectBigTypeId);
            }
            doChangeBigType(selectBigType);//默认加载
        },1000);    
    } else {
        //请求api
        getTypesByParentFun().then((result)=>{
            console.log('getTypesByParentFun result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);
                bigTypeArr.value = result.data;
                //默认选中的
                let selectBigType = bigTypeArr.value[0];
                // 如果是 在 HomeView 点击分类 跳转来的
                let selectBigTypeId = localStorage.getItem('selectBigTypeId');
                if(selectBigTypeId) {
                    //用完清除
                    localStorage.removeItem('selectBigTypeId');
                    selectBigType = bigTypeArr.value.find(t => t.id == selectBigTypeId);
                }
                doChangeBigType(selectBigType);//默认加载
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }
}
let currentBigType = null;
//切换大类别
function doChangeBigType(type) {
    if(currentBigType){
        currentBigType.selected = false;
        type.selected = true;
        currentBigType = type;
    } else {
        type.selected = true;
        currentBigType = type;
    }
    currentSecondType = null;
    //加载对应小类别
    doLoadSecondType();
    //重新加载
    currentPageNum.value = 1;
    productArr.value = [];
    pages.value = 0;
    doLoadDataProduct();
    doGoTop();
}

//右侧顶部小类别
const secondTypeArr = ref([]);
function doLoadSecondType() {
    //加载对应大类别下的所有小类别
    let parentId = currentBigType.id;
    if (window && window.enableDl) {
        //模拟
        setTimeout(()=>{
            let dataArr = [];
    
            for(let i=0;i<8;i++) {
                dataArr.push({id: i+1, name: parentId+'-小类别-'+(i+1), image: './default.png', parentId: parentId});
            }
    
            //成功后执行以下操作
            secondTypeArr.value = dataArr;
        },500);
    } else {
        //请求api
        getTypesByParentFun(parentId).then((result)=>{
            console.log('getTypesByParentFun result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);
                secondTypeArr.value = result.data;
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }
}
let currentSecondType = null;
//切换小类别
function doChangeSecondType(type) {
    if(currentSecondType){
        currentSecondType.selected = false;
        type.selected = true;
        currentSecondType = type;
    } else {
        type.selected = true;
        currentSecondType = type;
    }
    //重新加载数据
    currentPageNum.value = 1;
    productArr.value = [];
    pages.value = 0;
    doLoadDataProduct();
}

//搜索
const searchKey = ref('');
function doSearch(key) {
    console.log('doSearch:', key);
    if(!key || !key.trim()) {
        DlMessageBox.warning('请输入搜索内容');
        return;
    }
    if(productLoading.value) {
        DlMessageBox.warning('处理中！\n请稍候再试！');
        return;
    }
    searchKey.value = key;

    //重新搜索
    currentPageNum.value = 1;
    productArr.value = [];
    pages.value = 0;
    doLoadDataProduct();
}

//主菜单核心
const menuCore = inject('menuCore');
//去详情
function goDetail(product) {
    //详情页需要 productId
    localStorage.setItem('detailProductId', product.id);
    menuCore.push('/detail');
}

//购物车
const cart = inject('cart');
//加入购物车
function doAddCart(product) {
    //加入购物车
    if (window && window.enableDl) {
        //模拟
        if(cart[product.id]){
            cart[product.id].num++;
        } else {
            cart[product.id] = {productId: product.id, image: product.image, title: product.title, price: product.price, type: product.type, num: 1, checked: false};
        }
        //成功后执行以下操作
        DlMessageBox.success('加入成功');
        //console.log('cart:', cart);
    } else {
        //请求api
        addToCartFun(product.id, product.miaoShaId).then((result)=>{
            console.log('addToCartFun result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }
}

const viewBodyRef = ref(null);
const viewBodyHeight = computed(()=>{//计算展示区域高度
    let vh = 770;
    if(viewRef.value) {
        let p = viewRef.value.parentElement;
        vh = p.offsetHeight;
    }
    if(homeMenuBar.value) {
        let h = homeMenuBar.value.offsetHeight;
        vh -= h;
    }
    if(viewBodyRef.value) {
        let top = viewBodyRef.value.offsetTop;
        vh -= top;
    }
    return vh;
});

// 1 降序, -1 升序
const sortObj = reactive({
    all: {key:'all', selected: true, sort: 1}, //综合
    sell: {key:'sell',selected: false, sort: 1}, // 销量
    price: {key:'price',selected: false, sort: 1}, //价格
    time: {key:'time',selected: false, sort: 1} // 上架时间
});
let selectSort = sortObj.all;
//排序
function doChangeSort(selectObj) {
    //console.log('select:', selectObj);
    if(productLoading.value) {
        DlMessageBox.warning('处理中！\n请稍候再试！');
        return;
    }
    let selected = selectObj.selected;
    // 移除选中
    for(let key in sortObj) {
        sortObj[key].selected = false;
    }
    //切换排序规则
    if(selected) {
        selectObj.sort = -1*selectObj.sort;
    }
    selectObj.selected = true;
    selectSort = selectObj;

    doGoTop();
    //重新搜索
    currentPageNum.value = 1;
    productArr.value = [];
    pages.value = 0;
    doLoadDataProduct();
}

onMounted(()=> {
    doLoadBigType();
});

</script>
<template>
    <div class="view-dl" ref="viewRef" :style="'height:'+viewHeight+'px'">
        <div class="head-dl">
            <div class="top-title-dl">
                <div>分类搜索</div>
            </div>
            <SearchBox @search="doSearch" />
        </div>
        
        <div class="view-body-dl" ref="viewBodyRef" :style="'height:'+viewBodyHeight+'px'">
            <div class="left-type-list-dl">
                <div>
                    <div class="big-type-dl" :class="(t.selected?'big-type-active-dl':'')" v-for="t in bigTypeArr" :key="t.id" @click="doChangeBigType(t)">{{t.name}}</div>
                </div>
            </div>
            <div class="right-content-dl" @scroll="doChangeScroll">
                <div style="padding-bottom: 0.4rem;">
                    <div class="right-top-dl">
                        <div class="title-dl">{{(currentBigType ? currentBigType.name:'')}}:</div>
                        <div class="top-type-list-dl">
                            <div class="second-type-dl" :class="(t.selected?'second-type-active-dl':'')" v-for="t in secondTypeArr" :key="t.id" @click="doChangeSecondType(t)">
                                <div class="type-image-dl">
                                    <img :src="t.image" alt="no image">
                                </div>
                                <div class="type-title-dl">{{t.name}}</div>
                            </div>
                        </div>
                    </div>

                    <div class="right-data-dl">
                        <!-- 排序 -->
                        <div class="sort-list-dl">
                            <div class="sort-item" @click="doChangeSort(sortObj.all)" :class="(sortObj.all.selected?'sort-active-dl':'')">
                                <span>综合</span>
                                <IconTriangleDown v-if="sortObj.all.sort == 1" class="icon-dl" />
                                <IconTriangleUp v-else class="icon-dl" />
                            </div>
                            <div class="sort-item" @click="doChangeSort(sortObj.sell)" :class="(sortObj.sell.selected?'sort-active-dl':'')">
                                <span>销量</span>
                                <IconTriangleDown v-if="sortObj.sell.sort == 1" class="icon-dl" />
                                <IconTriangleUp v-else class="icon-dl" />
                            </div>
                            <div class="sort-item" @click="doChangeSort(sortObj.price)" :class="(sortObj.price.selected?'sort-active-dl':'')">
                                <span>价格</span>
                                <IconTriangleDown v-if="sortObj.price.sort == 1" class="icon-dl" />
                                <IconTriangleUp v-else class="icon-dl" />
                            </div>
                            <div class="sort-item" @click="doChangeSort(sortObj.time)" :class="(sortObj.time.selected?'sort-active-dl':'')">
                                <span>上架时间</span>
                                <IconTriangleDown v-if="sortObj.time.sort == 1" class="icon-dl" />
                                <IconTriangleUp v-else class="icon-dl" />
                            </div>
                        </div>

                        <div class="data-list-dl">
                            <template v-for="p in productArr" :key="p.id">
                                <ProductBox :product="p" @go-detail="goDetail" @add-cart="doAddCart" class="pfs-dl" />
                            </template>
                        </div>
                    </div>

                    <div class="load-box-dl" >
                        <!-- 加载中动画... -->
                        <DlLoading style="font-size: 1rem" v-show="productLoading" />
                        <div class="no-more-data-dl" v-show="!productLoading && noMoreData">暂无更多商品</div>
                    </div>
                </div>
            </div>
        </div>

        <div class="top-btn-dl" :style="topBtnStyle">
            <IconTopCircle class="icon-dl" @click="doGoTop" />
        </div>
    </div>
</template>
<style scoped>
.view-dl {
    font-size: 0.4rem;
    overflow: hidden;
}
.head-dl {
    background-color: #fff;
    padding: 0.14rem 0.38rem;
    margin-bottom: 0.1rem;
    font-size: 1rem;
    color: #333;
}
.top-title-dl {
    font-weight: bold;
    font-size: 0.6rem;
    text-align: center;
    position: relative;
}

.view-body-dl {
    display: flex;
}
.left-type-list-dl {
    flex-shrink: 0;
    width: 2.6rem;
    background-color: #fff;
    overflow: auto;
}
.big-type-dl {
    color: #000;
    padding: 0.1rem 0.2rem;
    text-align: center;
    margin: 0.2rem 0.1rem;
    cursor: pointer;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.big-type-active-dl {
    color: #fff;
    background-color: #000;
    border-radius: 0.1rem;
    font-weight: bold;
}

.right-content-dl {
    flex: 1 0 auto;
    margin-left: 0.2rem;
    height: 100%;
    overflow: hidden auto;
}
.right-top-dl {
    background-color: #fff;
    margin-bottom: 0.2rem;
    padding: 0.1rem;
    color: #333;
}
.title-dl {
    font-weight: bold;
    font-size: 0.4rem;
    margin-bottom: 0.28rem;
}
.top-type-list-dl {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-column-gap: 0.2rem;
    grid-row-gap: 0.2rem;
    min-height: 2.4rem;
    place-items: center;
}
.second-type-dl {
    text-align: center;
    cursor: pointer;
    border-radius: 0.2rem;
}
.second-type-active-dl {
    background-color: #ffdada;
    font-weight: bold;
}
.type-image-dl {
    width: 1.8rem;
    height: 1.8rem;
    overflow: hidden;
    margin: 0 auto;
}
.type-image-dl img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    font-size: 0.4rem;
    display: block;
}
.type-title-dl {
    font-size: 0.32rem;
    margin: 0.1rem 0;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.right-data-dl {
    background-color: #fff;
    color: #333;
}

.sort-list-dl {
    padding: 0.2rem 0.1rem;
    display: flex;
    justify-content: space-between;
    position: sticky;
    top: 0;
    background-color: #fff;
}
.sort-item {
    flex-shrink: 0;
    cursor: pointer;
    border: 1px solid #000;
    border-radius: 1rem;
    padding: 0 0.1rem;
}
.sort-item .icon-dl {
    width: 0.5rem;
    height: 0.5rem;
    vertical-align: top;
}
.sort-active-dl {
    color: #900;
}

.data-list-dl {
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-column-gap: 0.2rem;
    grid-row-gap: 0.2rem;
    margin-top: 0.1rem;
    place-items: center;
}


.pfs-dl {
    font-size: 1.6rem;
}

.load-box-dl {
    text-align: center;
    color: #aaa;
    margin-top: 0.5rem;
    padding: 0.2rem;
}
.load-box-dl .no-more-data-dl {
    font-size: 0.4rem;
    border-top: 1px solid #ccc;
    padding-top: 0.2rem;
}

.top-btn-dl {
    position: fixed;
    transition: all 0.2s linear;
}
.top-btn-dl .icon-dl {
    width: 1.6rem;
    height: 1.6rem;
    color: #fff;
    background-color: #999c;
    border-radius: 50%;
    cursor: pointer;
}
</style>